﻿using System;
using System.Linq;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ASBCC.Database.Entity;
using ASBCC.Database.Service;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using BEGDC.CC.Web.Workflow;
using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;

namespace BEGDC.CC.Web
{
    /// <summary>
    /// Summary description for main.
    /// </summary>
    public class MyProperty : BasePage
    {
        protected System.Web.UI.WebControls.Label lblLogin;
        protected System.Web.UI.WebControls.Label lblName;
        protected System.Web.UI.WebControls.Label lblNameChinese;

        protected System.Web.UI.WebControls.DataGrid dgDelegated;
        protected System.Web.UI.WebControls.DataGrid dgRoles;
        protected System.Web.UI.WebControls.LinkButton LinkButton1;
        protected System.Web.UI.WebControls.Label lblDepartment;

        protected System.Web.UI.WebControls.Repeater rptRoles;

        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                // Put user code to initialize the page here
                if (!Page.IsPostBack)
                {
                    this.GetUserInfo();
                    this.BindData();

                    UserDelegationTableEntitySet set1 = UserDelegationManager.SelectByCondition(string.Format("UserID = {0}", UserInfo.EmployeeID));
                    if (set1.Count > 0)
                    {

                        hidGuid1.Value = set1[0].UserDelegationID.ToString();
                        //txtDateFrom1.Text = set1[0].FromDate + "";
                        //txtDateTo1.Text = set1[0].ToDate + "";
                        lblDateFrom1.Text = set1[0].FromDate + "";
                        lblDateTo1.Text = set1[0].ToDate + "";

                        EmployeeTableEntitySet set2 = EmployeeManager.SelectByCondition(string.Format("EmployeeID = {0}", set1[0].DelegateTo));
                        if (set2.Count > 0)
                        {
                            //ss1.EmployeeID = set2[0].EmployeeNo;
                            //ss1.EmployeeName = set2[0].NameEN;
                            lblss1.Text = set2[0].NameEN;
                        }



                    }
                }

            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        private void GetUserInfo()
        {
            IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
            BEGDC.CC.Entity.Employee employee = iuser.GetUserByID(((CCIdentity)HttpContext.Current.User.Identity).UserInfo.Id);

            this.lblLogin.Text = employee.NameEN;
            this.lblName.Text = employee.NameCN;
            this.lblNameChinese.Text = employee.NameChinese;
            this.lblDepartment.Text = employee.Department.DepartmentCode;
        }

        private void BindData()
        {

            IQuery iquery = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            System.Data.DataTable dtRoles = iquery.QueryRoleList(((CCIdentity)HttpContext.Current.User.Identity).UserInfo.Id);

            this.dgRoles.DataSource = dtRoles;
            this.dgRoles.DataBind();


            System.Data.DataTable dtDelegates = iquery.QueryDelegatedList(((CCIdentity)HttpContext.Current.User.Identity).UserInfo.Id);

            this.dgDelegated.DataSource = dtDelegates;
            this.dgDelegated.DataBind();

        }


        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dgRoles.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgRoles_ItemDataBound);
            this.dgRoles.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgRoles_ItemCommand);

            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void dgRoles_ItemDataBound(object source, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {

                    ImageButton ibdelete = (ImageButton)e.Item.FindControl("imageDelete");

                    ibdelete.Attributes.Add("onclick", "return confirm('This item will be cancel delegation. Are you sure ?');");
                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        public void dgRoles_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            if (e.CommandName == "btnDelete")
            {
                string itemId = e.Item.Cells[0].Text;
                IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;


                BEGDC.CC.Entity.UserRole role = iuser.GetUserRoleByID(Convert.ToInt32(itemId));

                //Clear Cache
                if (role.DelegateEndDate == null) return;

                BEGDC.CC.BL.Workflow.CCPrincipal.RemovePrincipal(role.DelegateUser.NameEN);

                role.DelegateUser = null;
                role.DelegateStartDate = Nullables.NullableDateTime.Default;
                role.DelegateEndDate = Nullables.NullableDateTime.Default;
                role.IsEnabled = false;
                iuser.SaveUserRole(role);


                // Write Log
                IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
                CCIdentity id = this.User.Identity as CCIdentity;
                BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
                log.Module = "UserManagement";
                log.OperationType = "Delegation Role";
                Employee emp = new Employee();
                emp.Id = id.UserInfo.Id;
                log.Employee = emp;
                log.Time = System.DateTime.Now;
                log.Description = "[Delegation Role:Cancel Delegation";
                utility.SaveOperationLog(log);

                this.BindData();
            }
            else
            {
                this.BindData();
            }


        }

        protected System.Web.UI.WebControls.Button btnSave;
        protected System.Web.UI.WebControls.ImageButton btnDel1;
        protected System.Web.UI.WebControls.Label lblDateFrom1;
        protected System.Web.UI.WebControls.Label lblDateTo1;
        protected System.Web.UI.WebControls.HiddenField hidGuid1;
        protected System.Web.UI.WebControls.Label lblss1;

        /// <summary>
        /// 绑定代理设置
        /// </summary>


        ///// <summary>
        ///// 保存
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void btnSave_Click(object sender, EventArgs e)
        //{
        //    if (!string.IsNullOrEmpty(ss1.EmployeeID))
        //    {
        //        EmployeeTableEntity ent1 = EmployeeManager.SelectByKeys(ss1.EmployeeID);
        //        if (ent1 != null && ent1.EmployeeID != null)
        //        {
        //            UserDelegationTableEntitySet set1 = UserDelegationManager.SelectByCondition(string.Format("UserID = {0}", UserInfo.EmployeeID));
        //            if (set1.Count > 0)
        //            {
        //                set1[0].DelegateTo = ent1.EmployeeID;
        //                if (!string.IsNullOrEmpty(txtDateFrom1.Text))
        //                {
        //                    set1[0].FromDate = DateTime.Parse(txtDateFrom1.Text);
        //                }
        //                else
        //                {
        //                    set1[0].FromDate = null;
        //                }
        //                if (!string.IsNullOrEmpty(txtDateTo1.Text))
        //                {
        //                    set1[0].ToDate = DateTime.Parse(txtDateTo1.Text);
        //                }
        //                else
        //                {
        //                    set1[0].ToDate = null;
        //                }
        //                UserDelegationManager.Update(set1[0]);
        //            }
        //            else
        //            {
        //                UserDelegationTableEntity proxy1 = new UserDelegationTableEntity();
        //                proxy1.UserDelegationID = Guid.NewGuid();
        //                proxy1.CategoryName = "EZVisit";
        //                //proxy1.Disabled = "false";
        //                proxy1.DelegateTo = ent1.EmployeeID;
        //                if (!string.IsNullOrEmpty(txtDateFrom1.Text))
        //                {
        //                    proxy1.FromDate = DateTime.Parse(txtDateFrom1.Text);
        //                }
        //                if (!string.IsNullOrEmpty(txtDateTo1.Text))
        //                {
        //                    proxy1.ToDate = DateTime.Parse(txtDateTo1.Text);
        //                }
        //                proxy1.UserID = UserInfo.EmployeeID;
        //                UserDelegationManager.Insert(proxy1);

        //                hidGuid1.Value = proxy1.UserDelegationID.ToString();
        //            }
        //        }
        //    }
        //}

        protected void btnDel1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(hidGuid1.Value))
            {
                UserDelegationManager.Delete(new Guid(hidGuid1.Value));
                //ss1.EmployeeID = "";
                //ss1.EmployeeName = "";
                //txtDateTo1.Text = "";
                //txtDateFrom1.Text = "";
                lblss1.Text = "";
                lblDateFrom1.Text = "";
                lblDateTo1.Text = "";
            }
        }


        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);

            using (var dc = new ASBCC.Database.EntityFramework.CCEntities())
            {
                var user = dc.Employees.First(p => p.NameEN == User.Identity.Name && p.IsActived == true && p.IsEnabled == true);
                user.Roles.Load();
                rptRoles.DataSource = from t in user.Roles
                                      where !t.Disabled && t.Description != "+pcat+" && t.Description != "+country+"
                                      orderby t.BelongsTo, t.IsAdmin
                                      select t;
                rptRoles.DataBind();
            }
        }

        protected string GetRoleStyle(object dataItem)
        {
            return (bool)dataItem ? "role-admin" : "";
        }

        protected string IsCCSUser()
        {
            if (string.IsNullOrEmpty((User as CCPrincipal).Roles))
            {
                return "false";
            }
            if((User as CCPrincipal).Roles.Split(',').Length < 2)
            {
                return "false";
            }
            return "true";
        }

        protected string IsEZVisitUser()
        {
            using (var dc = new ASBCC.Database.EntityFramework.CCEntities())
            {
                foreach (var role in (User as ASBCC.Business.CSPrincipal).Role2s)
                {
                    int roleid;
                    if (!int.TryParse(role, out roleid)) continue;
                    ASBCC.Database.EntityFramework.Role r = dc.Roles.FirstOrDefault(p => p.RoleID == roleid);
                    if (r.BelongsTo == ASBCC.Business.SystemModule.EZVisit.ToString()) return "true";
                }
                return "false";
            }
        }

    }
}
